/**
 * @description  场外基金指令
 * @author shenhong
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message, Row, Col, Spin, Modal } from 'antd';
import { PrimaryGhostC, PrimaryC, FirstHeaderC, AvailableAssetC, TradeHoldC, TableC } from '../../../comps';
import FundName from './common/fundName'; // 基金简称
import FundInfo from './common/FundInfo'; // 基金基础信息
import Redeem from './common/redeem'; // 赎回规则
import AddBond from './common/addBond'; // 指令/簿记下达
import BuyRule from './common/buyRule'; // 买入规则
import style from './index.less';
import { uniqueKey } from '../../../utils/commonFunc';
@Form.create()
class FundTrade extends PureComponent {
  static defaultProps = {
    onRef: () => {},
    onChange: () => {},
    onOk: () => {},
    onCancel: () => {},
    type: '1',
  };
  constructor() {
    super();
    this.state = {
      currentUser: {}, // 当前登录用户信息
      querys: {}, // 发给接口的数据
      secucode: undefined, // 证券/基金代码
      portfolio: undefined, // 组合
      position: undefined, // 持仓
      money: undefined, // 资金可用
      Methed: '0', // 0-公募，1-私募
      infos: undefined, // 基金基础信息
      fundType: '0',
      isShow: false,
      query: {},
      trailColumns: [], //试算结果列表
      trailDataSource: [], //试算结果数据
      trailModel: false, //试算模态框
      productCode: undefined, //产品code
      portfolioCode: undefined, //组合code
      uid: '',
    };
  }

  componentDidMount() {
    this.props.onRef(this);
    const { dispatch } = this.props;
    dispatch({
      type: 'interBankBasicInfoM/getUserInfo',
      payload: localStorage.getItem('antd-pro-userId'), // 获取对当前用户信息
      callback: (res) => {
        this.setState({
          currentUser: res,
        });
      },
    });
    const uid = uniqueKey();
    uid.then((r) => {
      this.setState({ uid: r });
    });
  }

  // 基金变更事件
  secucodeOnChange = (e) => {
    this.setState({
      secucode: e,
    });
    if (e && e !== undefined) {
      const { dispatch } = this.props;
      const { fundType } = this.state;
      dispatch({
        type: 'newFundTrade/getFundInfo',
        payload: {
          secucode: e.secucode,
          type: fundType,
        },
        callback: (res) => {
          if (res.success == true) {
            this.setState({
              infos: res.data,
            });
          } else {
            message.error(res.errorMsg);
            this.setState({
              infos: undefined,
            });
          }
        },
      });
    } else {
      this.setState({
        infos: undefined,
      });
    }
  };

  // 组合变更事件
  portfolioOnChange = (e) => {
    this.setState({
      portfolio: e,
    });
    if (this.props.type == '1') this.queryIsAccountConfigured(e); //指令下达才进入这个判断
  };

  queryIsAccountConfigured = (value) => {
    if (value) {
      this.props.dispatch({
        //校验组合下是否有组合配置
        type: 'isAccountConfiguredM/queryIsAccountConfigured',
        payload: {
          portId: value,
        },
        callback: (data) => {
          if (data.result) {
            this.setState({
              isCanOrder: true,
            });
          } else {
            this.setState({
              isCanOrder: false,
            });
            message.warning(data.msg);
          }
        },
      });
    } else {
      this.setState({
        isCanOrder: true,
      });
    }
  };

  // 基金类型改变事件
  fundType = (e) => {
    this.setState({
      fundType: e,
    });
  };

  // 申请类型改变事件
  applyMethod = (e) => {
    this.setState({
      Methed: e,
    });
  };
  addData = () => {
    const { type } = this.props;
    const { position, money, currentUser, uid } = this.state;
    const data = this.Addbond.getInfo();
    if (data !== undefined) {
      const datas = _.cloneDeep(data);
      delete datas.fundInfo;
      delete datas.rollInCodeInfo;
      if (type == '10') {
        datas.portfolioId = datas.listId;
        datas.productId = null;
        delete datas.listId;
      }
      datas.isPublic = data.fundTypeSelect;
      datas.fundId = data.fundInfo.tradingCode;
      datas.securityId = data.fundInfo.tradingCode;
      datas.orderman = currentUser.userId;
      datas.exchangeCode = data.fundInfo.exchangeCode;
      datas.fundName = data.fundInfo.secuabbr;
      datas.rollInCode = data.rollInCodeInfo?.tradingCode;
      datas.rollnExchangeCode = data.rollInCodeInfo?.exchangeCode;
      datas.rollInName = data.rollInCodeInfo?.secuabbr;
      const query = {
        method: type == '1' || type == '10' ? null : '0',
        userId: currentUser.userId,
        userName: currentUser.name,
        trade5: datas,
        type: '5',
        remark: data.remark,
        uid: uid,
      };
      if (type == '1' || type == '2' || type == '11') {
        this.setState(
          {
            querys: query,
          },
          () => {
            if (query.trade5.applyMethod !== '2') {
              if (money.t1) {
                if (query.trade5.applyAmount < money.t1) {
                  this.setData();
                } else {
                  message.error('申请金额不能大于T+1可用资金');
                }
              } else {
                message.error('无可用资金');
              }
            } else {
              if (position.available) {
                if (query.trade5.applyNum <= position.available) {
                  this.setData();
                } else {
                  message.error('申请份额不能大于可用数量');
                }
              } else {
                message.error('无可用份额');
              }
            }
          },
        );
      } else if (type == '4') {
        this.setData();
      } else if (type == '10') {
        this.setState(
          {
            querys: query,
          },
          () => {
            this.setData();
          },
        );
      }
    }
  };
  // 点击下达或确定
  handleOnClick = () => {
    const { type } = this.props;
    const { currentUser, uid } = this.state;
    if (!this.state.isCanOrder && type == 1) {
      message.warning(this.props.errorSetMsg);
      return;
    }
    const data = this.Addbond.getInfo();
    if (data !== undefined) {
      const datas = _.cloneDeep(data);
      delete datas.fundInfo;
      delete datas.rollInCodeInfo;
      datas.trade5 = { ...datas };
      datas.trade5.isPublic = data.fundTypeSelect;
      datas.trade5.fundId = data.fundInfo.tradingCode;
      datas.trade5.exchangeCode = data.fundInfo.exchangeCode;
      datas.userName = currentUser.userId;
      datas.trade5.fundName = data.fundInfo.secuabbr;
      datas.trade5.rollInCode = data.rollInCodeInfo?.tradingCode;
      datas.trade5.rollnExchangeCode = data.rollInCodeInfo?.exchangeCode;
      datas.trade5.rollInName = data.rollInCodeInfo?.secuabbr;
      datas.trade5.fee = data.fee;
      if (type == '1') {
        this.setState({ query: datas }, () => {
          this.setState({ isShow: true });
        });
      } else {
        this.addData();
      }
    }
  };
  // 指令下达或新增簿记或交收
  setData = () => {
    const { dispatch, type, info } = this.props;
    const { querys } = this.state;
    if (type == '1') {
      dispatch({
        type: 'newFundTrade/SaveInstruction',
        payload: querys,
        callback: (res) => {
          this.props.onOk();
          this.Addbond.reset();
          this.setState({
            infos: undefined,
            portfolio: undefined,
            secucode: undefined,
            isShow: false,
            isCanOrder: true,
          });
          const uid = uniqueKey();
          uid.then((r) => {
            this.setState({ uid: r });
          });
        },
      });
    } else if (type == '2') {
      dispatch({
        type: 'newFundTrade/SaveInstructionw2',
        payload: querys,
        callback: (res) => {
          this.props.onOk();
          this.Addbond.reset();
          this.setState({
            infos: undefined,
            portfolio: undefined,
            secucode: undefined,
          });
          const uid = uniqueKey();
          uid.then((r) => {
            this.setState({ uid: r });
          });
        },
      });
    } else if (type == '4') {
      dispatch({
        type: 'newFundTrade/getTradeInstruction',
        payload: { id: info.id },
        callback: (res) => {
          this.props.onOk();
          this.Addbond.reset();
          this.props.onCancel();
          const uid = uniqueKey();
          uid.then((r) => {
            this.setState({ uid: r });
          });
        },
      });
    } else if (type == '10') {
      dispatch({
        type: 'newFundTrade/tradeBookSave',
        payload: querys,
        callback: (res) => {
          this.props.onOk();
          this.Addbond.reset();
          this.setState({
            infos: undefined,
            portfolio: undefined,
            secucode: undefined,
          });
          const uid = uniqueKey();
          uid.then((r) => {
            this.setState({ uid: r });
          });
        },
      });
    } else if (type == '11') {
      dispatch({
        type: 'portfolioTrialAddM/fundTradeSave',
        payload: querys,
        callback: (res) => {
          if (res && res.success == true) {
            this.props.onOk();
            this.Addbond.reset();
            this.setState({
              infos: undefined,
              portfolio: undefined,
              secucode: undefined,
            });
            message.success('组合试算新增成功');
          } else {
            message.error(res.errorMsg);
          }
          const uid = uniqueKey();
          uid.then((r) => {
            this.setState({ uid: r });
          });
        },
      });
    }
  };

  // 取消方法
  reset = () => {
    this.Addbond.reset();
    const { type } = this.props;
    this.setState({
      infos: undefined,
      portfolio: undefined,
      secucode: undefined,
      isCanOrder: true,
    });
    if (type == '4' || type == '2' || type == 'edit' || type == '10' || type == '11') {
      this.props.onCancel();
    }
  };
  //编辑的确定按钮
  editClick = () => {
    const data = this.Addbond.getInfo();
    if (!data) return;

    const applyAmount = data.applyAmount;
    const applyNum = data.applyNum;

    this.props.dispatch({
      type: 'newFundTrade/confirmEdit',
      payload: {
        id: this.props.info.id,
        applyAmount,
        applyNum,
      },
      callback: (res) => {
        if (res) {
          if (res.code == 0) {
            message.success('保存成功！');
            this.props.onCancel('refresh');
          } else {
            message.error(res.msg || '保存失败！');
          }
        } else {
          message.error('保存失败！');
        }
      },
    });
  };

  // 下方按钮
  showBtn = () => {
    const { type, loading } = this.props;
    if (type == '1' || type == '2' || type == '10' || type == '11') {
      let url =
        type == '1'
          ? 'newFundTrade/SaveInstruction'
          : type == '2'
          ? 'newFundTrade/SaveInstructionw2'
          : type == '11'
          ? 'portfolioTrialAddM/fundTradeSave'
          : 'newFundTrade/tradeBookSave';
      return (
        <div style={{ float: 'right', marginTop: '20px' }}>
          {/* {type == "2" && <PrimaryC
            loading={loading.effects['trailM/trialData'] === true}
            onClick={() => this.trialOnClick()}
            title={'试算'}
            style={{ marginRight: "10px" }}
          />} */}
          <PrimaryC loading={loading.effects[url] === true} onClick={() => this.handleOnClick()} title={type == 1 ? '下达' : '确定'} />
          <PrimaryGhostC onClick={() => this.reset()} title='取消' style={{ marginLeft: '10px' }} />
        </div>
      );
    } else if (type == '4') {
      return (
        <div style={{ float: 'right', marginTop: '20px' }}>
          <PrimaryC loading={loading.effects['newFundTrade/getTradeInstruction'] === true} onClick={() => this.handleOnClick()} title={'交收'} />
          <PrimaryGhostC onClick={() => this.reset()} title='取消' style={{ marginLeft: '10px' }} />
        </div>
      );
    } else if (type == 'edit') {
      return null;
      // <div style={{ float: "right", marginTop: '20px' }}>
      //   <PrimaryC
      //     loading={loading.effects['newFundTrade/confirmEdit'] === true}
      //     onClick={() => this.editClick()}
      //     title={'保存'}
      //   />
      //   <PrimaryGhostC
      //     onClick={() => this.reset()}
      //     title="取消"
      //     style={{ marginLeft: "10px" }}
      //   />
      // </div>
    }
  };

  // 系列产品变更
  seriesProductsOnChange = (e) => {};
  // 二次确认点击确定
  handleOk = () => {
    this.addData();
  };
  // 二次确认点击取消
  handleCancel = () => {
    this.setState({
      isShow: false,
    });
  };

  // 二次确认model框
  showModel = () => {
    const { query, isShow } = this.state;
    const { loading } = this.props;
    const modalProps = {
      visible: isShow,
      title: '确认下达',
      width: 700,
    };
    return (
      <div style={{ marginLeft: '200px' }}>
        <Modal {...modalProps} onOk={this.handleOk} onCancel={this.handleCancel} confirmLoading={loading.effects['newFundTrade/SaveInstruction'] === true}>
          <AddBond type={'3'} info={query} />
        </Modal>
      </div>
    );
  };
  //投资类型改变响应
  investmentChange = () => {};
  //试算按钮点击
  trialOnClick = () => {
    const { currentUser, productCode, portfolioCode } = this.state;
    const { type, dispatch } = this.props;
    const data = this.Addbond.getInfo();
    if (data !== undefined) {
      const datas = _.cloneDeep(data);
      delete datas.fundInfo;
      delete datas.rollInCodeInfo;
      datas.userName = currentUser.userId;
      datas.isPublic = data.fundTypeSelect;
      datas.fundId = data.fundInfo.tradingCode;
      datas.securityId = data.fundInfo.tradingCode;
      datas.orderman = currentUser.userId;
      datas.exchangeCode = data.fundInfo.exchangeCode;
      datas.fundName = data.fundInfo.secuabbr;
      datas.rollInCode = data.rollInCodeInfo?.tradingCode;
      datas.rollnExchangeCode = data.rollInCodeInfo?.exchangeCode;
      datas.rollInName = data.rollInCodeInfo?.secuabbr;
      const query = {
        method: type == '1' || type == '10' ? null : '0',
        userId: currentUser.userId,
        userName: currentUser.name,
        productCode: productCode, //产品code
        portfolioCode: portfolioCode, //组合code
        tenant: currentUser.tenant, //租户code
        trade5: datas,
        type: '5',
        remark: data.remark,
        businessType: '5',
      };
      this.setState({ trailModel: true }, () => {
        dispatch({
          type: 'trailM/trialData',
          payload: query,
          callback: (res) => {
            if (res) {
              this.setState({
                trailColumns: res.columns,
                trailDataSource: res.dataSource,
              });
            } else {
              this.setState({
                trailColumns: [],
                trailDataSource: [],
              });
            }
          },
        });
      });
    }
  };
  //获取组合code
  portfolioCode = (e) => {
    if (e) {
      this.setState({ portfolioCode: e });
    } else this.setState({ portfolioCode: undefined });
  };
  //获取产品code
  productCode = (e) => {
    if (e) {
      this.setState({ productCode: e });
    } else this.setState({ productCode: undefined });
  };

  // 页面内容渲染
  showComponent = () => {
    const { type, info, listId, loading } = this.props;
    const { portfolio, secucode, money, infos, isShow } = this.state;
    if (type == '1' || type == '2' || type == '11') {
      return (
        <div style={{ overflow: 'hidden' }}>
          <Row>
            <Spin spinning={loading.effects['newFundTrade/getFundInfo'] == true}>
              <FundName info={infos} />
            </Spin>
          </Row>
          <Row className={style.index}>
            <Col span={12}>
              <FirstHeaderC title='基金基础信息' />
              <div style={{ marginBottom: '10px' }}>
                <Spin spinning={loading.effects['newFundTrade/getFundInfo'] == true}>
                  <FundInfo info={infos} />
                </Spin>
              </div>
              <FirstHeaderC title='买入规则' />
              <div style={{ marginBottom: '10px' }}>
                <Spin spinning={loading.effects['newFundTrade/getFundInfo'] == true}>
                  <BuyRule info={infos} />
                </Spin>
              </div>
              <FirstHeaderC title='赎回规则' />
              <div>
                <Spin spinning={loading.effects['newFundTrade/getFundInfo'] == true}>
                  <Redeem info={infos} />
                </Spin>
              </div>
            </Col>
            <Col span={12}>
              <div style={{ marginBottom: '10px' }}>
                <AvailableAssetC
                  portfolio={portfolio}
                  onChange={(e) => {
                    // 资金值改变触发事件
                    this.setState({
                      money: e,
                    });
                  }}
                />
              </div>
              <div style={{ marginBottom: '10px' }}>
                <TradeHoldC
                  securityType={'2'} //场外基金
                  portfolio={portfolio}
                  tradingcode={secucode && secucode.tradingCode ? secucode.tradingCode : undefined}
                  exchangecode={secucode && secucode.exchangeCode ? secucode.exchangeCode : undefined}
                  onChange={(e) => {
                    this.setState(
                      {
                        position: { ...e },
                      },
                      () => {
                        this.Addbond.changeinvestmentType();
                      },
                    );
                  }}
                />
              </div>
              <FirstHeaderC title={'交易要素'} />
              <div style={{ marginTop: '10px', height: '50px' }}>
                <AddBond
                  // info={1}
                  fundType={(e) => this.fundType(e)}
                  onRef={(ref) => (this.Addbond = ref)}
                  portfolioOnChange={(e) => this.portfolioOnChange(e)}
                  secucodeOnChange={(e) => this.secucodeOnChange(e)}
                  applyMethod={(e) => this.applyMethod(e)}
                  type={type}
                  portfolioCode={this.portfolioCode}
                  productCode={this.productCode}
                  position={this.state.position}
                />
                <div>{this.showBtn()}</div>
                <div>{isShow ? <div>{this.showModel()}</div> : null}</div>
              </div>
            </Col>
          </Row>
        </div>
      );
    } else if (type == '3' || type == '4' || type == 'edit' || type == 10) {
      return (
        <div>
          {type == '4' && <FirstHeaderC title={'簿记下达'} />}
          <div style={{ marginTop: '10px', height: '50px' }}>
            <AddBond
              info={info}
              type={type}
              listId={listId}
              fundType={(e) => {}}
              onRef={(ref) => (this.Addbond = ref)}
              portfolioOnChange={(e) => this.portfolioOnChange(e)}
              secucodeOnChange={(e) => this.secucodeOnChange(e)}
              seriesProductsOnChange={(e) => this.seriesProductsOnChange(e)}
              applyMethod={(e) => this.applyMethod(e)} // 申请类型改变事件
              investmentChange={this.investmentChange}
              position={this.state.position}
            />
            <div>{this.showBtn()}</div>
          </div>
        </div>
      );
    }
  };
  //试算结果列表优化
  trailColumnsChange = (data) => {
    if (data) {
      data?.map((item) => {
        if (item.key == 'ruleDesc') {
          item.ellipsis = true;
        } else {
          item.width = '125px';
        }
      });
    }
    return data;
  };
  //试算结果
  showTrail = () => {
    const { trailModel, trailColumns, trailDataSource } = this.state;
    const newTrailColumns = this.trailColumnsChange(trailColumns);
    return (
      <Modal
        visible={trailModel}
        title='试算结果'
        width={1200}
        onOk={() => {
          this.setState({ trailModel: false });
        }}
        onCancel={() => {
          this.setState({ trailModel: false });
        }}
      >
        <TableC
          columns={newTrailColumns}
          dataSource={trailDataSource}
          loading={this.props.loading.effects['trailM/trialData'] === true}
          scroll={{ y: '231px' }}
          rowKey='id'
          hidePage={true}
        />
      </Modal>
    );
  };
  render() {
    const { isShow, trailModel } = this.state;
    return (
      <div>
        {this.showComponent()}
        {trailModel && this.showTrail()}
      </div>
    );
  }
}

export default connect(({ newFundTrade, interBankBasicInfoM, portfolioTrialAddM, loading, trailM, isAccountConfiguredM }) => ({
  newFundTrade,
  interBankBasicInfoM,
  portfolioTrialAddM,
  loading,
  trailM,
  errorSetMsg: isAccountConfiguredM.msg,
  isAccountConfiguredM,
}))(FundTrade);
